﻿namespace Manhua3.Helper
{
    using HtmlAgilityPack;
    using SharpCompress.Compressor;
    using SharpCompress.Compressor.Deflate;
    using System.IO;
    using System.Net.Http;
    using System.Threading.Tasks;

    public class XHttpClient
    {
        private class MyHttpHeaders : HttpClientHandler
        {
            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
            {
                request.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.92 Safari/537.4");
                request.Headers.Add("Accept-Encoding", "gzip");
                return base.SendAsync(request, cancellationToken);
            }
        }

        public static async Task<HtmlDocument> GetHtmlDocumentAsync(string url)
        {
            using(var client = new HttpClient(new MyHttpHeaders()))
            using(var response = await client.GetAsync(url))
            using (var stream = await response.Content.ReadAsStreamAsync())
            using(var ms = new MemoryStream())
            {
                var result = new HtmlDocument();

                try
                {
                    byte[] buffer = new byte[4096];
                    int len;
                    while ((len = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, len);
                    }

                    ms.Seek(0, SeekOrigin.Begin);

                    GZipStream zip = new GZipStream(
                            ms,
                            CompressionMode.Decompress);
                    result.Load(zip);
                }
                catch
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    result.Load(ms);
                }

                return result;
            }

            //HtmlDocument html = new HtmlDocument();
            //HttpWebRequest request = WebRequest.CreateHttp(url);
            //request.Accept = "text/html, application/xhtml+xml, */*";
            //request.Headers["Accept-Encoding"] = "gzip";            
            //using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
            //using (Stream stream = response.GetResponseStream())
            //using (MemoryStream ms = new MemoryStream())
            //{
            //    #region 读取html
            //    try
            //    {
            //        byte[] buffer = new byte[4096];
            //        int len;
            //        while ((len = stream.Read(buffer, 0, buffer.Length)) > 0)
            //        {
            //            ms.Write(buffer, 0, len);
            //        }

            //        ms.Seek(0, SeekOrigin.Begin);

            //        if (response.Headers["Content-Encoding"] != null &&
            //            response.Headers["Content-Encoding"].Contains("gzip"))
            //        {
            //            GZipStream zip = new GZipStream(
            //                    ms,
            //                    CompressionMode.Decompress);
            //            html.Load(zip);
            //        }
            //        else
            //        {
            //            html.Load(ms);
            //        }
            //    }
            //    catch
            //    {
            //        ms.Seek(0, SeekOrigin.Begin);
            //        html.Load(ms);
            //    }

            //    #endregion
            //}

            //return html;
        }
    }
}
